<template>
  <div class="detail-page">
    <!-- 面包屑导航 -->
    <el-breadcrumb class="breadcrumb" separator="/" fade-in>
      <el-breadcrumb-item :to="{ path: '/scoring/history' }">评分历史</el-breadcrumb-item>
      <el-breadcrumb-item>评分详情</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="page-title slide-in">任务详情 #{{ taskId }}</div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="6" animated />
    </div>

    <!-- 详情内容 -->
    <div v-else-if="taskDetail" class="detail-content">
      <!-- 基本信息 -->
      <el-card class="info-card scale-in" shadow="never">
        <template #header>
          <div class="card-header">
            <el-icon class="header-icon"><InfoFilled /></el-icon>
            <span>任务基本信息</span>
          </div>
        </template>

        <el-row :gutter="24">
          <el-col :span="12">
            <div class="info-item">
              <label>任务ID：</label>
              <span class="info-value">{{ taskDetail.task_info.task_id }}</span>
            </div>
            <div class="info-item">
              <label>患者编号：</label>
              <span class="info-value">{{ taskDetail.patient.patient_code }}</span>
            </div>
            <div class="info-item">
              <label>患者性别：</label>
              <span class="info-value">{{ taskDetail.patient.gender_name }}</span>
            </div>
            <div class="info-item">
              <label>出生日期：</label>
              <span class="info-value">{{ taskDetail.patient.birthday || '未知' }}</span>
            </div>
          </el-col>

          <el-col :span="12">
            <div class="info-item">
              <label>提交医生：</label>
              <span class="info-value">{{ taskDetail.doctor.real_name }}</span>
            </div>
            <div class="info-item">
              <label>科室：</label>
              <span class="info-value">{{ taskDetail.doctor.department }}</span>
            </div>
            <div class="info-item">
              <label>职称：</label>
              <span class="info-value">{{ taskDetail.doctor.title || '无' }}</span>
            </div>
            <div class="info-item">
              <label>任务状态：</label>
              <el-tag :type="getStatusTagType(taskDetail.task_info.status)" size="small">
                {{ taskDetail.task_info.status_name }}
              </el-tag>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 时间信息 -->
      <el-card class="time-card" shadow="never">
        <template #header>
          <div class="card-header">
            <el-icon class="header-icon"><Clock /></el-icon>
            <span>时间信息</span>
          </div>
        </template>

        <el-row :gutter="24">
          <el-col :span="12">
            <div class="info-item">
              <label>提交时间：</label>
              <span class="info-value">{{ taskDetail.task_info.submit_time }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>完成时间：</label>
              <span class="info-value">{{ taskDetail.task_info.complete_time || '未完成' }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 原始数据 -->
      <el-card class="data-card" shadow="never">
        <template #header>
          <div class="card-header">
            <el-icon class="header-icon"><Document /></el-icon>
            <span>原始数据</span>
          </div>
        </template>

        <el-row :gutter="24">
          <el-col :span="12">
            <div class="info-item">
              <label>内镜图像：</label>
              <div class="image-container" v-if="taskDetail.task_info.image_url">
                <el-image
                  :src="getImageUrl(taskDetail.task_info.image_url)"
                  :preview-src-list="[getImageUrl(taskDetail.task_info.image_url)]"
                  class="preview-image"
                  fit="cover"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                      <span>图像加载失败</span>
                    </div>
                  </template>
                </el-image>
              </div>
              <span v-else class="no-image">无图像</span>
            </div>
          </el-col>

          <el-col :span="12">
            <div class="info-item">
              <label>临床文本信息：</label>
              <div class="clinical-text">
                {{ taskDetail.task_info.clinical_text || '无临床信息' }}
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- AI分析结果 -->
      <el-card v-if="taskDetail.ai_result" class="result-card" shadow="never">
        <template #header>
          <div class="card-header">
            <el-icon class="header-icon"><DataAnalysis /></el-icon>
            <span>AI分析结果</span>
          </div>
        </template>

        <el-descriptions
          :column="2"
          border
          class="result-descriptions"
        >
          <el-descriptions-item label="AI评分值" :span="1">
            <div class="score-display">
              <el-tag type="primary" size="large" class="score-tag">
                <span class="score-display">{{ taskDetail.ai_result.score }}</span> 分
              </el-tag>
            </div>
          </el-descriptions-item>

          <el-descriptions-item label="严重程度" :span="1">
            <el-tag
              :type="getSeverityTagType(taskDetail.ai_result.severity)"
              size="large"
              class="severity-tag"
            >
              {{ taskDetail.ai_result.severity_name }}
            </el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="置信度" :span="2">
            <div class="confidence-container">
              <el-progress
                :percentage="taskDetail.ai_result.confidence"
                :color="getConfidenceColor(taskDetail.ai_result.confidence)"
                :stroke-width="8"
                class="confidence-progress"
              />
              <span class="confidence-text">{{ taskDetail.ai_result.confidence }}%</span>
            </div>
          </el-descriptions-item>

          <el-descriptions-item label="模型版本" :span="2">
            <el-tag type="info">{{ taskDetail.ai_result.model_version }}</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="AI分析详情" :span="2">
            <div class="analysis-details">
              {{ taskDetail.ai_result.analysis_details }}
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 医生复核结果 -->
      <el-card v-if="taskDetail.review_result" class="review-card" shadow="never">
        <template #header>
          <div class="card-header">
            <el-icon class="header-icon"><UserFilled /></el-icon>
            <span>医生复核结果</span>
          </div>
        </template>

        <el-descriptions :column="2" border>
          <el-descriptions-item label="复核评分">
            <el-tag type="warning" size="large">
              <span class="score-display">{{ taskDetail.review_result.reviewed_score }}</span> 分
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="复核意见" :span="2">
            <div class="review-notes">
              {{ taskDetail.review_result.reviewed_notes || '无复核意见' }}
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 未找到结果 -->
      <el-card v-else-if="taskDetail.task_info.status === 4" class="failed-card" shadow="never">
        <el-result
          icon="error"
          title="分析失败"
          sub-title="AI分析过程中出现错误，请稍后重试"
        >
          <template #extra>
            <el-button type="primary" @click="goToNewScoring">
              <el-icon><Refresh /></el-icon>
              重新评分
            </el-button>
          </template>
        </el-result>
      </el-card>

      <!-- 分析中状态 -->
      <el-card v-else-if="taskDetail.task_info.status === 2" class="analyzing-card" shadow="never">
        <div class="analyzing-content">
          <el-icon class="analyzing-icon"><Loading /></el-icon>
          <div class="analyzing-text">
            <h3>AI分析进行中...</h3>
            <p>正在进行智能分析，请稍候...</p>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 未找到任务 -->
    <el-card v-else-if="!loading" class="not-found-card" shadow="never">
      <el-result
        icon="warning"
        title="任务不存在"
        sub-title="未找到指定的评分任务"
      >
        <template #extra>
          <el-button type="primary" @click="goToHistory">
            <el-icon><Back /></el-icon>
            返回列表
          </el-button>
        </template>
      </el-result>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import {
  InfoFilled,
  Clock,
  Document,
  DataAnalysis,
  UserFilled,
  Loading,
  Refresh,
  Back,
  Picture
} from '@element-plus/icons-vue'

const store = useStore()
const route = useRoute()
const router = useRouter()

// 获取任务ID
const taskId = computed(() => Number(route.params.taskId))

// 状态
const loading = computed(() => store.state.scoring.isLoading)
const taskDetail = computed(() => store.state.scoring.currentTask)

// 轮询定时器
let pollingTimer: NodeJS.Timeout | null = null

// 获取图像URL - 使用相对路径通过Vite代理访问
const getImageUrl = (path: string) => {
  if (!path) return ''
  if (path.startsWith('http')) return path
  // 直接返回相对路径，让Vite代理处理
  return path
}

// 获取任务详情
const fetchTaskDetail = async () => {
  if (taskId.value) {
    await store.dispatch('scoring/getTaskResult', taskId.value)
  }
}

// 轮询任务状态
const startPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
  }

  pollingTimer = setInterval(async () => {
    await fetchTaskDetail()

    const task = taskDetail.value
    if (task && (task.task_info.status === 3 || task.task_info.status === 4)) {
      // 任务完成或失败，停止轮询
      if (pollingTimer) {
        clearInterval(pollingTimer)
        pollingTimer = null
      }
    }
  }, 3000) // 每3秒轮询一次
}

// 获取状态标签类型
const getStatusTagType = (status: number) => {
  const typeMap = {
    1: 'info',     // 待处理
    2: 'warning',  // 分析中
    3: 'success',  // 已完成
    4: 'danger'    // 失败
  }
  return typeMap[status] || 'info'
}

// 获取严重程度标签类型
const getSeverityTagType = (severity: number) => {
  const typeMap = {
    1: 'success', // 缓解期
    2: '',        // 轻度
    3: 'warning', // 中度
    4: 'danger'   // 重度
  }
  return typeMap[severity] || 'info'
}

// 获取置信度颜色
const getConfidenceColor = (confidence: number) => {
  if (confidence >= 90) return '#67C23A'
  if (confidence >= 80) return '#E6A23C'
  return '#F56C6C'
}

// 导航方法
const goToHistory = () => {
  router.push('/scoring/history')
}

const goToNewScoring = () => {
  router.push('/scoring/new')
}

// 页面加载
onMounted(async () => {
  await fetchTaskDetail()

  // 如果任务还在分析中，开始轮询
  const task = taskDetail.value
  if (task && (task.task_info.status === 1 || task.task_info.status === 2)) {
    startPolling()
  }
})

// 组件卸载时清理
onUnmounted(() => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
  }
})
</script>

<style scoped>
.detail-page {
  padding: 0;
}

.breadcrumb {
  margin-bottom: 16px;
  font-size: 14px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e0e0e0;
}

.loading-container {
  padding: 20px;
}

/* 卡片通用样式 */
.info-card,
.time-card,
.data-card,
.result-card,
.review-card,
.failed-card,
.analyzing-card,
.not-found-card {
  border-radius: 12px;
  border: 1px solid #e0e0e0;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #303133;
}

.header-icon {
  margin-right: 8px;
  color: #409eff;
}

/* 信息项样式 */
.info-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item label {
  min-width: 80px;
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
}

.info-value {
  flex: 1;
  color: #303133;
  word-break: break-all;
}

/* 图像展示 */
.image-container {
  width: 200px;
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e0e0e0;
  background-color: #f5f5f5;
}

.preview-image {
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  font-size: 12px;
}

.image-error .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.no-image {
  color: #c0c4cc;
  font-style: italic;
}

/* 临床文本 */
.clinical-text {
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409eff;
  color: #606266;
  line-height: 1.6;
  min-height: 60px;
  max-height: 200px;
  overflow-y: auto;
}

/* AI结果样式 */
.result-descriptions {
  margin: 0;
}

.score-display {
  display: flex;
  align-items: center;
}

.score-tag,
.severity-tag {
  font-size: 18px;
  font-weight: 600;
  padding: 8px 16px;
}

.confidence-container {
  display: flex;
  align-items: center;
  gap: 16px;
}

.confidence-progress {
  flex: 1;
}

.confidence-text {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  min-width: 50px;
  text-align: right;
}

.analysis-details {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  background-color: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  border-left: 4px solid #409eff;
  max-height: 200px;
  overflow-y: auto;
}

.review-notes {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  background-color: #fdf6ec;
  padding: 12px;
  border-radius: 6px;
  border-left: 4px solid #E6A23C;
  max-height: 150px;
  overflow-y: auto;
}

/* 分析中状态 */
.analyzing-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60px 20px;
  text-align: center;
}

.analyzing-icon {
  font-size: 48px;
  color: #409eff;
  animation: spin 2s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.analyzing-text h3 {
  font-size: 18px;
  color: #303133;
  margin: 0 0 8px 0;
}

.analyzing-text p {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

/* Element Plus 样式覆盖 */
:deep(.el-card__header) {
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  background-color: #fafafa;
  width: 120px;
}

:deep(.el-descriptions__content) {
  padding: 12px 16px;
}

:deep(.el-result__title) {
  font-size: 20px;
  color: #303133;
}

:deep(.el-result__subtitle) {
  color: #909399;
  font-size: 14px;
}

:deep(.el-skeleton) {
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-title {
    font-size: 20px;
    margin-bottom: 16px;
  }

  .info-card,
  .time-card,
  .data-card,
  .result-card,
  .review-card {
    margin-bottom: 16px;
  }

  :deep(.el-card__body) {
    padding: 16px;
  }

  :deep(.el-descriptions) {
    --el-descriptions-table-border: 1px solid #ebeef5;
  }

  :deep(.el-descriptions__label) {
    width: 80px;
    font-size: 13px;
  }

  :deep(.el-descriptions__content) {
    padding: 8px 12px;
    font-size: 13px;
  }

  .image-container {
    width: 120px;
    height: 120px;
  }

  .confidence-container {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }

  .confidence-text {
    text-align: center;
  }

  .analyzing-content {
    padding: 40px 20px;
  }
}
</style>